import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

// 解决重复导航错误
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(path) {
  return originalPush.call(this, path).catch((err) => err)
}

const routes = [
  // 根路径重定向到登录页面
  { path: '/', redirect: '/login' },
  // 登录和注册页面
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/Register.vue')
  },
  // 管理端路由
  {
    // 管理端路由 - 使用Home作为布局组件
    path: '/admin',
    name: 'admin',
    component: () => import('../views/public/Home.vue'),
    redirect: '/admin/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        meta: {
          title: '首页',
          icon: 'el-icon-s-home'
        },
        component: () => import('../views/admin/Dashboard.vue')
      },
      {
        path: 'user',
        name: 'User',
        meta: {
          title: '用户管理',
          icon: 'el-icon-user'
        },
        component: () => import('../views/admin/User.vue')
      },
      {
        path: 'book',
        name: 'Book',
        meta: {
          title: '书籍管理',
          icon: 'el-icon-reading'
        },
        component: () => import('../views/admin/Book.vue')
      },
      {
        path: 'borrow-records',
        name: 'BorrowRecords',
        meta: {
          title: '借阅记录',
          icon: 'el-icon-document-copy'
        },
        component: () => import('../views/admin/BorrowRecords.vue')
      },
      {
        path: 'book-stats',
        name: 'BookStats',
        meta: {
          title: '图书订阅',
          icon: 'el-icon-data-line'
        },
        component: () => import('../views/admin/BookStats.vue')
      },
      {
        path: 'bookshelf',
        name: 'Bookshelf',
        meta: {
          title: '书架管理',
          icon: 'el-icon-film'
        },
        component: () => import('../views/admin/BookShelf.vue')
      },
      {
        path: 'category',
        name: 'Category',
        meta: {
          title: '类别管理',
          icon: 'el-icon-collection-tag'
        },
        component: () => import('../views/admin/Category.vue')
      },
      {
        path: 'subscription-notifiy',
        name: 'SubScriptionNotifiy',
        meta: {
          title: '订阅通知',
          icon: 'el-icon-bell'
        },
        component: () => import('../views/admin/SubscriptionNotifiy.vue')
      },
      {
        path: 'reader-suggestions',
        name: 'ReaderSuggestions',
        meta: {
          title: '读者建议',
          icon: 'el-icon-chat-dot-round'
        },
        component: () => import('../views/admin/ReaderSuggestions.vue')
      },
      {
        path: 'notice',
        name: 'Notice',
        meta: {
          title: '公告管理',
          icon: 'el-icon-message'
        },
        component: () => import('../views/admin/Notice.vue')
      },
      {
        path: 'behavior-logs',
        name: 'BehaviorLogs',
        meta: {
          title: '行为日志',
          icon: 'el-icon-timer'
        },
        component: () => import('../views/admin/BehaviorLogs.vue')
      }
    ]
  },
  // 用户端路由
  {
    path: '/user',
    name: 'user',
    component: () => import('../views/public/Home.vue'),
    redirect: '/user/recommend',
    // 移除不必要的meta.requiresAuth和role，因为已通过路径前缀实现权限控制
    children: [
      {
        path: 'recommend',
        name: 'Recommend',
        meta: {
          title: '推荐',
          icon: 'el-icon-s-flag'
        },
        component: () => import('../views/user/Recommend.vue')
      },
      {
        path: 'borrow',
        name: 'Borrow',
        meta: {
          title: '借阅',
          icon: 'el-icon-s-order'
        },
        component: () => import('../views/user/Borrow.vue')
      },
      {
        path: 'review',
        name: 'Review',
        meta: {
          title: '我的评论',
          icon: 'el-icon-s-comment'
        },
        component: () => import('../views/user/Review.vue')
      },
      {
        path: 'history',
        name: 'History',
        meta: {
          title: '浏览历史',
          icon: 'el-icon-s-promotion'
        },
        component: () => import('../views/user/History.vue')
      },
      {
        path: 'collection',
        name: 'Collection',
        meta: {
          title: '我的收藏',
          icon: 'el-icon-star-on'
        },
        component: () => import('../views/user/Collection.vue')
      },
      {
        path: 'category',
        name: 'Category',
        meta: {
          title: '图书分类',
          icon: 'el-icon-share'
        },
        component: () => import('../views/user/Category.vue')
      },
      {
        path: 'bookshelf',
        name: 'Bookshelf',
        meta: {
          title: '我的书架',
          icon: 'el-icon-s-management'
        },
        component: () => import('../views/user/Bookshelf.vue')
      },
      {
        path: 'subscription',
        name: 'Subscription',
        meta: {
          title: '订阅',
          icon: 'el-icon-message-solid'
        },
        component: () => import('../views/user/Subscription.vue')
      },
      {
        path: 'profile',
        name: 'Profile',
        meta: {
          title: '个人资料',
          icon: 'el-icon-s-tools'
        },
        component: () => import('../views/user/Profile.vue')
      }
    ]
  },

  // 404页面路由 - 放在具体路由前，通配符路由前
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('../views/public/404.vue')
  },
  // 捕获所有未匹配的路由并重定向到404页面
  { path: '*', redirect: '/404' }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 白名单
const whiteList = ['/login', '/register', '/404']

// 路由守卫
router.beforeEach((to, from, next) => {
  const isPublicRoute = whiteList.includes(to.path)
  if (isPublicRoute) {
    next()
    return
  }

  // 用户认证检查
  const userInfo = getUserInfoOrRedirect(next)
  if (!userInfo) {
    return false
  }

  // 权限验证 - 简化为仅基于路径前缀的权限控制
  if (!validateUserPermission(to, userInfo.role, next)) {
    return false
  }
  next()
})

/**
 * 获取用户信息，如果不存在则重定向到登录页面
 * @param {Function} next - 路由next函数
 * @returns {Object|null} 用户信息对象或null（如果已重定向）
 */
function getUserInfoOrRedirect(next) {
  try {
    const userInfoStr = localStorage.getItem('userInfo')
    if (!userInfoStr) {
      console.log('未找到用户信息，重定向到登录页面')
      next('/login')
    }
    const userInfo = JSON.parse(userInfoStr)
    return userInfo
  } catch (error) {
    localStorage.removeItem('userInfo')
    next('/login')
  }
}

/**
 * 验证用户是否具有访问指定路由的权限
 * @param {Object} to - 目标路由对象
 * @param {string} userRole - 用户角色
 * @param {Function} next - 路由next函数
 * @returns {boolean} 是否具有权限
 */
function validateUserPermission(to, userRole, next) {
  // 简化版：仅通过路径前缀进行权限控制
  // 移除了冗余的meta角色权限检查，因为已经通过路径前缀实现了相同的控制
  if (to.path.startsWith('/admin') && userRole !== 'admin') {
    console.log('权限不足：普通用户无法访问管理端页面')
    next('/404')
    return false
  } else if (to.path.startsWith('/user') && userRole !== 'user') {
    console.log('权限不足：管理员无法访问用户端页面')
    next('/404')
    return false
  }
  return true
}

export default router
